<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Article
 *
 * @property int $id
 * @property string $title
 * @property string $body
 * @property string $url_provider
 * @property bool $is_show
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property string $key_word
 * @property string $video_code
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Episode[] $episodes
 * @property-read mixed $article_icon
 * @property-read mixed $article_type
 * @property-read mixed $coverage_url
 * @property-read mixed $excerpt
 * @property-read mixed $fname
 * @property-read mixed $image_count
 * @property-read mixed $jsonld_logo
 * @property-read mixed $related_articles
 * @property-read mixed $seo_word
 * @property-read mixed $show_list
 * @property-read mixed $site_url
 * @property-read mixed $tag_list
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Image[] $images
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Movie[] $movies
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Show[] $shows
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Tag[] $tags
 * @property-read \App\Vote $vote
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereBody($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereHtmlCode($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereIsShow($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereKeyWord($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereMobileCode($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereTitle($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereUrlFlash($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereUrlProvider($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereUrlVideo($value)
 * @mixin \Eloquent
 * @property string $discription
 * @property string $deleted_at
 * @property int $read_count 浏览次数
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereCoverageId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereDeletedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereDiscription($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereReadCount($value)
 * @property string $raw_title 爬去的标题
 * @property string $raw_content 爬去的内容
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereRawContent($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereRawTitle($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Article whereVideoCode($value)
 */
class Article extends Model
{
    use SoftDeletes;
    /**
     * 应该被调整为日期的属性
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
    protected $touches = ['tags'];
    const DEFAULT_ARTICLE_COVERAGE_KEY = 'default-article.png';
    protected $fillable = [
        'title',
        'body',
        'url_video',
        'url_provider',
        'url_flash',
        'raw_title',
        'raw_content',
        'is_show',
        'show_id',
        'key_word',
        'video_code',
        'description',
        'coverage_uri',
        'video_title',
    ];

    public static function boot()
    {
        parent::boot();


        self::created(function ($model) {
            // ... code here
            $article_id = $model->id;
            $vote = Vote::firstOrNew(compact('article_id'));
            $vote->visit = rand(1444, 2999);
            $vote->fake_read = $vote->visit;
            $vote->score = rand(35, 45) / 10;
            $vote->vote_count = rand(122, 355);
            $vote->favorate_count = rand(122, 350);
            //var_dump($vote);
            $vote->save();

            //设置tag
            $tags = [];
            if (strpos($model->raw_title, '评')) {
                $tags[] = 8;
            }
            if (strpos($model->raw_title, '报告')) {
                $tags[] = 9;
            }
            if (strpos($model->url_provider, 'zmnedu')) {
                $tags[] = 1;
            }
            //不含图片 长度小于300字符
            if (strpos($model->raw_content, 'img') === false && strlen($model->raw_content) < 300) {
                $tags[] = 20;
            }

            if (strpos($model->url_provider, 'cnbeta')) {
                $tags[] = 5;
            }

            if (empty($tags)) {
                $tags[] = 5;
            }
            $model->tags()->sync($tags);
        });


        self::deleted(function ($model) {
            // ... code here
            Image::where(['article_id' => $model->id])->delete();
        });

    }

    /**
     * 创建美剧蜘蛛通用方法
     * @param string $raw_title
     * @param string $raw_content
     * @param string $provider_url
     * @param array $image_urls
     * @param null $keyword
     * @param null $description
     */
    static function Spider_Insert(string $raw_title, string $raw_content, string $url_provider, array $img_urls): Article
    {
        $unique_condition = compact('raw_title', 'url_provider');
        $data = array_filter(compact('raw_title', 'raw_content'));
        $instance = Article::withTrashed()->where($unique_condition)->first();
        if (!$instance) {
            $instance = (new Article())->newInstance($unique_condition);
        }
        //文章已删除就不进行写入
        if ($instance->deleted_at) {
            return $instance;
        }


        $instance->timestamps = $instance->id < 1; //更新的时候不修改时间戳
        $instance->fill($data)->save();

        //保存图片封面
        array_filter($img_urls);
        foreach ($img_urls as $index => $img_url) {
            $key = "article/{$instance->id}/img/{$index}";
            $image = Image::fetchUrlWithKey($img_url, $key, $raw_title);
            if ($image->id > 0) {
                $image->article_id = $instance->id;
                $image->save();
                //第一张图片设置封面
                if ($index == 0 && empty($instance->coverage_uri)) {
                    $instance->coverage_uri = $image->key;
                    $instance->save();
                }
            }
        }
        return $instance;
    }

    public function setBodyAttribute($value)
    {
        $paterns = ['#;{2,}#', '#&nbsp;*#'];
        $value = preg_replace($paterns, '', $value);
        $value = strip_tags($value, '<quote><img><div><pre><ul><li><ol><iframe><embed><video><object><table><td><tr><tbody><th><thead><p><br><hr><h1><h2><h3><h4><h5><span><strong><i>');
        $this->attributes['body'] = trim($value);
    }

    public function vote()
    {
        return $this->hasOne('App\Vote');
    }

    public function movies()
    {
        return $this->belongsToMany('App\Movie');
    }

    public function episodes()
    {
        return $this->belongsToMany('App\Episode');
    }

    public function shows()
    {
        return $this->belongsToMany('App\Show');
    }

    public function getTagListAttribute()
    {
        return $this->tags->pluck('id')->toArray();
    }

    public function getShowListAttribute()
    {
        return $this->shows->pluck('id')->toArray();
    }

    public function getFnameAttribute()
    {
        return $this->images->pluck('fname');
    }


    public function setRawTitleAttribute($value)
    {
        if (empty($this->title)) {
            $this->title = $value;
        }
        $this->attributes['raw_title'] = $value;
    }

    public function setRawContentAttribute($value)
    {
        if (empty($this->body)) {
            $this->body = $value;
        }
        $this->attributes['raw_content'] = $value;
    }

    public function setTitleAttribute($value)
    {
        $value = preg_replace('#[\<\[]+#', '『', $value);
        $value = preg_replace('#[\>\]]+#', '』', $value);
        $this->attributes['title'] = $value;
    }

    public function getCoverageUrlAttribute()
    {
        $baseUrl = config('app.QNImageUrl');
        if ($this->coverage_uri) {
            $key = $this->coverage_uri;
        } else {//没有剧照就显示default
            $key = self::DEFAULT_ARTICLE_COVERAGE_KEY;
        }
        return $baseUrl . '/' . $key;
    }

    public function getJsonldLogoAttribute()
    {
        $w = 800;
        $h = 450;
        $images = $this->images();
        if ($images->count() != 0) {//有照片就显示照片
            return $images->first()->imageWH($w, $h);
        } elseif ($this->show) {//有剧集就显示剧照
            return $this->show->coverage_url;
        } else {//没有剧照就显示default
            $waterMaker = 'imageView2/1/w/' . $w . '/h/' . $h;
            $baseUrl = config('app.QNImageUrl');
            return $baseUrl . '/' . $this->default_article_key . '?' . $waterMaker;
        }
    }

    public function images()
    {
        return $this->hasMany('App\Image')->orderBy('updated_at', 'desc');
    }

    public function setKeyWordAttribute($value)
    {
        $value = trim($value);
        if (strlen($value)) {
            $this->attributes['key_word'] = $value;
        } else {
            $this->attributes['key_word'] = 'news.trytv.org';
        }
    }

    public function getSiteUrlAttribute()
    {
        return env('APP_URL') . '/article/' . $this->id;
    }

    //创建 搜索关键字
    public function getSeoWordAttribute()
    {

        $this->tags();
        $keyWord = $this->key_word;
        foreach ($this->tags as $tag) {
            $keyWord = '   ' . $tag->name;
        }
        if ($this->show) {
            $keyWord .= $this->show->name_en . '  ' . $this->show->name_zh;

        }
        return $keyWord;
    }

    public function tags()
    {
        return $this->belongsToMany('App\Tag')->withTimestamps();
    }

    public function getExcerptAttribute()
    {
        if (strlen($this->discription) > 2) {
            return $this->discription;
        }


        $body = strip_tags($this->body);
        return str_limit($body, 300);
    }

    public function getArticleTypeAttribute()
    {
        if (strlen($this->video_code) > 4) {
            return 'glyphicon glyphicon-facetime-video';
        } else {
            return 'glyphicon glyphicon-picture';
        }
    }

    public function getImageCountAttribute()
    {
        if ($this->images()->count()) {
            return '共' . $this->images()->count() . '张图片';
        } else {
            return '';
        }
    }

    public function getArticleIconAttribute()
    {
        if (strlen($this->video_code) > 10) {
            return 'glyphicon glyphicon-film';
        } elseif ($this->images()->count() > 2) {
            return 'glyphicon glyphicon-picture';
        } else {
            return 'glyphicon glyphicon-text-size';
        }
    }

    public function getRelatedArticlesAttribute()
    {

        $pattern = '#([\s\|\(\)\?\:\/]|《|》|：|）)+#';
        $key = preg_replace($pattern, ' ', $this->key_word);
        $key = trim($key);
        if (strlen($key) < 1) return;
        $keyWords = preg_split('#\s+#', $key);
        $regexString = '';
        foreach ($keyWords as $word) {
            if (strlen($word) > 1) {
                $regexString .= "($word)|";
            }
        }
        $regexString = trim($regexString, '|');
        $articles = Article::where('title', 'REGEXP', $regexString)->whereNotIn('id', [$this->id])
            ->orderBy('updated_at', 'desc')->limit(15)
            ->get();
        return $articles;
    }

    public function safeInsertSEO($keyword, $description)
    {
        if (!empty($this->key_word)) {
            $this->key_word = $keyword;
        }
        if (!empty($this->description)) {
            $this->description = $description;
        }
        $this->save();
        return $this;
    }
}
